from django.db.models.signals import post_save
from django.dispatch import receiver

from social.feed.models import Post
from social.search.models import EsPost


@receiver(post_save, sender=Post)
def post_post_save(sender, instance: Post, created, **kwargs):
    if created:
        EsPost.new_instance(instance)
    else:
        p = EsPost.get(instance.id, ignore=404)
        if not p:
            EsPost.new_instance(instance)
        else:
            if not instance.is_active:
                EsPost.delete(p)
            else:
                update_fields = kwargs.get('update_fields', set())
                if update_fields and not set(EsPost.related_user_fields()).intersection(set(update_fields)):
                    # 没有需要变动es的，无需更新
                    return
                update_map = {
                    frozenset({'like_count'}): lambda: {'like_count': instance.like_count},
                    frozenset({'comment_count'}): lambda: {'comment_count': instance.comment_count},
                }
                update_func = update_map.get(update_fields, None)
                if update_func:
                    p.update(**update_func())
